require 'fileutils'
require 'qiniu'
require 'digest'
require 'openssl'
require 'base64'
require 'time'
require 'net/http'
require 'uri'
class CommonApi < Grape::API
	$redis = Redis.new()
	#通用接口
	version 'v1', using: :path
	format :json
	default_format :json
	formatter :json, Grape::Formatter::Rabl
	resource :common do
		URL_QN = "http://file.hanrunkeji.com"
		desc '图片上传接口'
	    params do
	    	requires :myfile, type: File
	    end
		post 'upload' do
			tmp = params[:myfile]['tempfile']
			random_url = CommonApi::random_string + params[:myfile]['filename']
			file = File.join("public/upload", random_url)
			FileUtils.cp tmp.path, file
			bucket = 'hanrunkejitest'
			key = random_url
			put_policy = Qiniu::Auth::PutPolicy.new(
    		bucket,      # 存储空间
    		key,     # 最终资源名，可省略，即缺省为“创建”语义，设置为nil为普通上传
    		3600    #token过期时间，默认为3600s
			)
			uptoken = Qiniu::Auth.generate_uptoken(put_policy)
			local_file = file
			code, result, response_headers = Qiniu::Storage.upload_with_token(uptoken, local_file, bucket, key)
			puts code
			puts result
	  		puts response_headers     # => 'image/png'
					code, result, response_headers = Qiniu::Storage.stat(
		    		bucket,     # 存储空间
		    		key         # 资源名
					)
			primitive_url = 'http://file.hanrunkeji.com/'+key
			download_url = Qiniu::Auth.authorize_download_url(primitive_url)
			{code: '0', msg: 'ok', url: download_url}
		end

		desc '头像修改接口'
		params do
			optional :user_name, type: String, desc: '登录用户名(手机号/身份证号)'
			optional :passwd, type: String, desc: '密码'
			optional :avatar, type: File, desc: '头像'
		end
		post 'upload_avatar' do
			content_type 'application/x-www-form-urlencoded'
			if params[:user_name].nil?
				{code: '400', msg: '请输入手机号或身份证号'}
			elsif params[:passwd].nil?
				{code: '400', msg: '请输入密码'}
			elsif params[:avatar].nil?
				{code: '400', msg: '请提交文件'}
			else
				file = params[:avatar]
				passwd = Digest::MD5.hexdigest(CommonApi::des_decrypt(params[:passwd]))
				if (/(^\d{15}$)|(^\d{17}([0-9]|X))$/ =~ params[:user_name].to_s) == 0
					user = User.where(identity_card: identity_card, encrypted_password: passwd).first
				  # user = User.where(identity_card: identity_card).first
				else
					user = User.where(phone: params[:user_name], encrypted_password: passwd).first
					# user = User.where(phone: params[:user_name]).first
				end
				if user.nil?
					{code: '400', msg: '用户名或密码错误'}
				else
					user_detail = UserDetail.where(user_id: user.id).first
					url = CommonApi::random_string + file['filename']

					code = CommonApi::url_post(file, url)
					if code == 200
						url = CommonApi::URL_QN + "/" + url
						user_detail.head_img_url =  url
						user_detail.save
						{code: '0', msg: 'OK', url: url}
					else
						{code: '400', msg: '上传失败'}
					end
				end
			end
		end

		desc '身份证照片上传接口'
		params do
			optional :user_name, type: String, desc: '登录用户名(手机号/身份证号)'
			optional :passwd, type: String, desc: '密码'
			optional :identity_card, type: String, desc: '身份证号'
			optional :identity_img01, type: File, desc: '身份证01'
			optional :identity_img02, type: File, desc: '身份证02'
		end
		post 'upload_identity' do
			content_type 'application/x-www-form-urlencoded'
			if params[:user_name].nil?
				{code: '400', msg: '请输入手机号或身份证号'}
			elsif params[:passwd].nil?
				{code: '400', msg: '请输入密码'}
			elsif params[:identity_card].nil?
				{code: '400', msg: '请输入身份证号'}
			elsif params[:identity_img01].nil? || params[:identity_img02].nil?
				{code: '400', msg: '请提交文件'}
			else
				file01 = params[:identity_img01]
				file02 = params[:identity_img02]
				passwd = Digest::MD5.hexdigest(CommonApi::des_decrypt(params[:passwd]))
				identity_card = CommonApi::des_decrypt(params[:identity_card])
				if(/(^\d{15}$)|(^\d{17}([0-9]|X))$/ =~identity_card.to_s) == 0
					if (/(^\d{15}$)|(^\d{17}([0-9]|X))$/ =~ params[:user_name].to_s) == 0
						user = User.where(identity_card: identity_card, encrypted_password: passwd).first
					  # user = User.where(identity_card: identity_card).first
					else
						user = User.where(phone: params[:user_name], encrypted_password: passwd).first
						# user = User.where(phone: params[:user_name]).first
					end
					if user.nil?
						{code: '400', msg: '用户名或密码错误'}
					else
						user_detail = UserDetail.where(user_id: user.id).first
						url01 = CommonApi::random_string + file01['filename']
						url02 = CommonApi::random_string + file02['filename']
						code01 = CommonApi::url_post(file01, url01)
						code02 = CommonApi::url_post(file02, url02)
						if code01 == 200 && code02 == 200
							url01 = CommonApi::URL_QN + "/" + url01
							url02 = CommonApi::URL_QN + "/" + url02
							url = url01 + ";" + url02
							user_detail.certification_img = url
							user.identity_card = identity_card
							user_detail.validate_type = 1
							if user.save && user_detail.save
								{code: '0', msg: 'OK', identity_img01: url01, identity_img02: url02}
							else
								{code: '400', msg: '更新失败'}
							end
						else
							{code: '400', msg: '上传失败'}
						end
					end
				else
					{code: '400', msg: '身份证号格式错误'}
				end
			end
		end
		# 工种查询接口
		# 用于用户信息更新时，拉取工单列表
		# 参数:
		# 请求方式: get
		# 返回: 工种列表
		#
		desc '工种列表接口'
		get 'jobs' do
			@jobs = Job.all
			if @jobs.empty?
				{code: '400', msg: '无可显示工种'}
			else
				render rabl: "jobs"
			end
		end

		# 公告查询接口
		# 用于首页公告滚动
		# 参数:
		# 请求方式: get
		# 返回: 公告列表
		#
		desc '公告列表接口'
		get 'announcements' do
			@announcements = Announcement.all
			if @announcements.empty?
				{code: '400', msg: '无可显示工种'}
			else
				render rabl: "announcements"
			end
		end
		desc '劳务公司接口'
		get 'companies' do
			@companies = Company.all
			if @companies.empty?
				{code: '400', msg: '无可显示工种'}
			else
				render rabl: "companies"
			end
		end
		desc '申请加入劳务派遣'
		params do
			optional :user_id, type: String, desc: '用户ID'
		end
		post 'join_laowu' do
			{code: '0', msg: 'OK'}
		end

		# 广告查询接口
		# 用于首页公告滚动
		# 参数:
		# 请求方式: get
		# 返回: 广告
		#
		desc '广告列表接口'
		get 'ad' do
			ad = Ad.last
			if ad.nil?
				{code: '400', msg: '无可显示工种'}
			else
				{code:'0', msg: 'OK', ad:{id: ad.id, name: ad.name, url: ad.url}}
			end
		end
		desc '短信验证码'
		params do
			optional :phone, type: Integer, desc: '用户手机号'
		end

		get 'send_sms' do
			# :yunpian
			#   如果content(第二个参数) 是字符串
			#     调用 通用接口 发送短信
			#   如果是 Hash
			#     调用 模板接口 发送短信
			#     可选参数：
			#       :tpl_id 默认是 2
			if params[:phone].nil?
				{code: '400', msg: '请收入手机号'}
			else
				if (/^1[345678]\d{9}$/ =~ params[:phone].to_s).nil? # 验证手机号码是否正确
					{code: '400', msg: '手机号码不正确'}
				else
					if $redis.get(params[:phone])
						identifying_code = $redis.get(params[:phone])
					else
						identifying_code = [1,2,3,4,5,6,7,8,9,0].sample(6).join
						 # 验证码 5分钟有效
						$redis.set(params[:phone], identifying_code)
					end
					apikey = '90efeac1c5d58c0b57d325098059041e'
					params['apikey'] = apikey
					params['mobile'] = params[:phone]
					send_tpl_sms_uri = URI.parse('https://sms.yunpian.com/v2/sms/tpl_single_send.json')
					params['tpl_id'] = 2766544
					params['tpl_value'] = URI::escape('#code#') + '=' + URI.encode_www_form_component(identifying_code)
					response = Net::HTTP.post_form(send_tpl_sms_uri, params)
					{code: '0', msg: 'OK'}
				end
			end
		end
		def self.send_yzm(name, encrypted_password, url, phone)
			apikey = '90efeac1c5d58c0b57d325098059041e'
			params = Hash.new
			params['apikey'] = apikey
			params['mobile'] = phone
			send_tpl_sms_uri = URI.parse('https://sms.yunpian.com/v2/sms/tpl_single_send.json')
			params['tpl_id'] = 2782460

			params['tpl_value'] = URI::escape('#name#') + '=' + URI.encode_www_form_component(name) + "&" + URI::escape('#passwd#') + '=' + URI.encode_www_form_component(encrypted_password) + "&" + URI::escape('#url#') + '=' + URI.encode_www_form_component(url)
			response = Net::HTTP.post_form(send_tpl_sms_uri, params)
			{code: '0', msg: 'OK'}
		end
		desc '测试用'
		get 'test' do
			#puts WorkManageService.sub_contractor_upload(50,1)
			# puts WorkManageService.project_team(23,50)
			# YiBuService.cj_yb()
			# YiBuService.qy_yb()
			# YiBuService.ry_yb()
			# YiBuCommitService.cj_qr
			# YiBuService.bz_yb()
			# YiBuCommitService.bz_qr()
			# YiBuService.ry_yb
			# YiBuCommitService.ht_qr
			# YiBuCommitService.ry_qr
			# YiBuCommitService.jtc_qr
			# YiBuService.px_yb()
			# YiBuService.jtc_yb()
			# YiBuCommitService.bz_qr()
			# CommonApi.send_yzm("张三", "123", "http:aa.aa", 13808970140)
			# YiBuCommitService.ry_qr()
			MakeExcel.project_excel(93)
		end

		def random_string
			o = [('a'..'z'),('A'..'Z')].map{|i| i.to_a}.flatten;
			(0...50).map{ o[rand(o.length)] }.join;
		end

		def des_encrypt(des_text)
		  des = OpenSSL::Cipher.new("DES-ECB")
		  des.encrypt
		  des.key = '(b4@x*b%'
		  result = des.update(des_text)
		  result << des.final
		  # str = ""
		  # result.each_byte {|c| str += ("%02x" % c);}
		  # return str
			return Base64.encode64(result).gsub(/\n/, '')
		end
		def des_decrypt(des_text)
			str = Base64.decode64(des_text)
		  	des = OpenSSL::Cipher.new("DES-ECB")
		  	des.decrypt
		  	des.key = '(b4@x*b%'
		  #result = des.update([str].pack('H*'))
			result = des.update(str)
		  	result << des.final
		  return result
		end
		def url_post(file,url)
			tmp = file['tempfile']
			file = File.join("public/upload", url)
			FileUtils.cp tmp.path, file
			bucket = 'hanrunkejitest'
			key = url
			put_policy = Qiniu::Auth::PutPolicy.new(
    		bucket,      # 存储空间
    		key,     # 最终资源名，可省略，即缺省为“创建”语义，设置为nil为普通上传
    		3600    #token过期时间，默认为3600s
			)
			uptoken = Qiniu::Auth.generate_uptoken(put_policy)
			local_file = file
			code, result, response_headers = Qiniu::Storage.upload_with_token(uptoken, local_file, bucket, key)
			puts code
			puts result
			return code
		end
		def path_post(file_path, file_name)
			bucket = 'hanrunkejitest'
			key = file_name
			put_policy = Qiniu::Auth::PutPolicy.new(
				bucket,      # 存储空间
				key,     # 最终资源名，可省略，即缺省为“创建”语义，设置为nil为普通上传
				3600    #token过期时间，默认为3600s
			)

			uptoken = Qiniu::Auth.generate_uptoken(put_policy)
			local_file = File.open(file_path)
			code, result, response_headers = Qiniu::Storage.upload_with_token(uptoken, local_file, bucket, key)
			return code
		end
		def file_post(file)
			tmp = file['tempfile']
			file = File.join("public/upload", url)
			FileUtils.cp tmp.path, file
			bucket = 'hanrunkejitest'
			key =  file['tempfile']
			put_policy = Qiniu::Auth::PutPolicy.new(
    		bucket,      # 存储空间
    		key,     # 最终资源名，可省略，即缺省为“创建”语义，设置为nil为普通上传
    		3600    #token过期时间，默认为3600s
			)
			uptoken = Qiniu::Auth.generate_uptoken(put_policy)
			local_file = file
			code, result, response_headers = Qiniu::Storage.upload_with_token_2(uptoken, local_file, bucket, key)
			puts code
			puts result
			return code
		end
		def delete_file(file)
			bucket = 'hanrunkejitest'
			key = file
			code, result, response_headers = Qiniu::Storage.delete(
			    bucket,     # 存储空间
			    key         # 资源名
			)
			puts result
			puts response_headers
			return code
		end
		# 工种ID转工种方法
		def cover_job(job_id)
			job = Job.where(id: job_id).first
			if job.nil?
				return ""
			else
				return job.name
			end
		end
		def cover_city(code)
			city = Division.where(code: code).first
			if city.nil?
				return ""
			else
				pro_code = code.to_s[0,2] + "0000"
				province = Division.where(code: pro_code).first
				if province.nil?
					return city.name
				else
					return province.name + city.name
				end
			end
		end

		def cover_ethnicity(ethnicity_id)

			i = ethnicity_id.to_i - 1
			file = Rails.root.to_s + '/db/race.json'
			city_date = JSON.parse(File.read(file))
			puts city_date[i]
			return city_date[i]
		end

		def format_time(timestamp)
			time = Time.at timestamp
			year = time.year.to_s
			month = time.month.to_s
			day = time.day.to_s
			return year + '-' + month + '-' + day
		end

		def format_time_new(time)
			year = time.year.to_s
			month = time.month.to_s
			day = time.day.to_s
			return year + '-' + month + '-' + day
		end

		def self.calculated_latitude(lat1,lng1,lat2,lng2)
			lat1 = lat1.to_i
			lng1 = lng1.to_i
			lat2 = lat2.to_i
			lng2 = lng2.to_i
			include Math
			lat_diff = (lat1 - lat2)*PI/180.0
			lng_diff = (lng1 - lng2)*PI/180.0
			lat_sin = Math.sin(lat_diff/2.0) ** 2
			lng_sin = Math.sin(lng_diff/2.0) ** 2
			first = Math.sqrt(lat_sin + Math.cos(lat1*PI/180.0) * Math.cos(lat2*PI/180.0) * lng_sin)
			result = Math.asin(first) * 2 * 6378137.0
			result.to_i
		end
		# def city
		# 	city_date = JSON.parse(File.read('/Users/yudagong/rails_app/construction_personnel_credit2/db/areas.json'))
		# 	province =  city_date['province']
		# 	city = city_date['city']
		# 	province.each do |pro|
		# 		division = Division.new
		# 		division.code = pro['id']
		# 		division.name = pro['text']
		# 		division.type = 1
		# 		division.save
		# 	end
		# 	city.each do |c|
		# 		division = Division.new
		# 		division.code = c['id']
		# 		division.name = c['text']
		# 		division.type = 2
		# 		division.save
		# 	end
		# end
		
	end
	def self.month_days(year, month)
		if [1,3,5,7,8,10,12].include?(month.to_i)
			return 31
		elsif month.to_i == 2
			if (year.to_i % 4) == 0
				return 29
			else
				return 28
			end
		else
			return 30
		end
	end
	def self.jiami_aes(key, data)
		key = key
		iv = key[0,16]
		data = data
		# AES.encrypt(data, key, {:iv => iv, :padding => "pkcs7", :length => 128}) 
		cipher = OpenSSL::Cipher::AES256.new(:CBC)
	    cipher.encrypt
	    cipher.key =
	    cipher.key = key
	    cipher.iv = iv
	    cipher.iv = key[0,16]
	    encrypted = cipher.update(data) + cipher.final
	    return Base64.strict_encode64(encrypted).to_s 	
	end
	def self.cover_bank_name_to_code(bank_name)
		bank = Bank.where("bank_name like ?", "%"+bank_name+"%").first
		if bank.nil?
			return bank.bank_code
		else
			return "104"
		end
	end
	def self.cover_bank_code_to_name(bank_code)
		bank = Bank.where("bank_code = ?", bank_code).first
		if bank.nil?
			return ""
		else
			return bank.bank_name
		end
		
	end
	def self.cover_worker_type_to_name(worker_type)
		
		if worker_type.to_i == 10
			return "管理人员"
		else
			return "建筑工人"
		end
		
	end
	def self.cover_contract__type_to_name(contract__type)
		if contract__type.nil?
			return "其他类型合同"
		else
			if contract__type.to_i == 1
				return "固定期限合同"
			else
				return "以完成一定工作为期限的合同"
			end
		end
		
		
	end

	def self.cover_politics_type_to_name(politics_type)
		case politics_type
		when 1
			politics_type = "中共党员" 
		when 13
		  politics_type = "群众"
		when 2
			politics_type = "中共预备党员"
		when 3
			politics_type = "共青团员"
		when 4
			politics_type = "民革党党员"
		else
		  	politics_type = "其他"
		end
		return politics_type
	end
	def self.cover_culture_leve_to_name(culture_leve)
		case culture_leve
		when 1
			culture_leve = "小学" 
		when 2
		  culture_leve = "初中"
		when 3
			culture_leve = "高中"
		when 4
			culture_leve = "中专"
		when 5
			culture_leve = "大专"
		when 6
			culture_leve = "本科"
		when 7
			culture_leve = "硕士"
		when 8
			culture_leve = "博士"
		else
		  	culture_leve = "其他"
		end
		return culture_leve
	end
	def self.cove_project_type_name(project_type)
		case project_type
		when 1
			project_type_name = "房屋建筑工程" 
		when 2
		  project_type_name = "市政公用工程"
		when 3
			project_type_name = "机电安装工程"
		when 4
			project_type_name = "铁路工程"
		when 5
			project_type_name = "公路工程"
		when 6
			project_type_name = "港口与航道工程"
		when 7
			project_type_name = "水利水电工程"
		when 8
			project_type_name = "电力工程"
		when 9
			project_type_name = "矿山工程"
		when 10
			project_type_name = "冶炼工程"
		when 11
			project_type_name = "化工石油工程"
		when 12
			project_type_name = "通信工程"	
		else
		  	project_type_name = "其他"
		end
		return project_type_name
	end
	def self.cove_project_status_to_name(project_status)
		case project_status
		when 1
			project_status_name = "筹备" 
		when 2
		  project_status_name = "在建"
		when 3
			project_status_name = "完工"
		when 4
			project_status_name = "停工"
		else
		  	project_status_name = "其他"
		end
		return project_status_name
	end
	def self.cove_job_to_name(job_id)
		case job_id

		when 20
			job_name = "钢筋工"	
		when 30
			job_name = "架子工"		
		when 40
			job_name = "混凝土工"		
		when 50
			job_name = "模板工"	
		when 60
			job_name = "机械设备安装工"	
		when 70
			job_name = "通风工"	
		when 160
			job_name = "桩机操作工"		
		when 80
			job_name = "安装起重工"		
		when 90
			job_name = "安装钳工"	
		when 100
			job_name = "电气设备安装调试工"		
		when 110
			job_name = "管道工"	
		when 120
			job_name = "变电安装工"	
		when 130
			job_name = "建筑电工"		
		when 140
			job_name = "司泵工"		
		when 170
			job_name = "起重信号工"	
		when 160
			job_name = "桩机操作工"		
		when 150
			job_name = "挖掘铲运和桩工机械司机"		
		when 180
			job_name = "建筑起重机械安装拆卸工"	
		when 190
			job_name = "装饰装修工"		
		when 200
			job_name = "室内成套设施安装工"	
		when 290
			job_name = "除尘工"	
		when 280
			job_name = "爆破工"		
		when 270
			job_name = "电焊工"	
		when 250
			job_name = "石工"	
		when 240
			job_name = "木工"
		when 230
			job_name = "防水工"		
		when 220
			job_name = "幕墙制作工"	
		when 210
			job_name = "建筑门窗幕墙安装工"	
		when 310
			job_name = "线路架设工"		
		when 320
			job_name = "古建筑传统石工"	
		when 330
			job_name = "古建筑传统瓦工"	
		when 340
			job_name = "古建筑传统彩画工"
		when 350
			job_name = "古建筑传统木工"		
		when 360
			job_name = "古建筑传统油工"
		when 10
			job_name = "砌筑工" 
		when 1000
		  job_name = "其它"
		when 390
			job_name = "杂工"
		when 900
			job_name = "管理人员"
		else
		  	job_name = "其他"
		end
		return job_name
	end
	def self.verify_login(user_name, passwd)
		passwd = Digest::MD5.hexdigest(CommonApi::des_decrypt(passwd))
		if (/(^\d{15}$)|(^\d{17}([0-9]|X))$/ =~ user_name.to_s) == 0
			user = User.where(identity_card: user_name, encrypted_password: passwd).first
		else
			user = User.where(phone: user_name, encrypted_password: passwd).first
		end
		if user.nil?
			return -1
		else
			return user.id
		end
	end

	def self.cover_job_to_string(job_id)
		job = job_id.to_s
		if job.length == 2
			return job = "0"+job
		else
			return job
		end
	end
	def self.cover_certificate_type(type_id)
		file = Rails.root.to_s + '/db/certificate.json'
		certificate_type_date = JSON.parse(File.read(file))
	    certificate_type_date['secode_type'].each do |sct| 
	   	   if sct["id"] == type_id.to_i
	   	   		return sct["name"]
	   	   end
	    end
	end
end
